/**
 *
 * FileName 文件名称 默认下载Excel
 * FileStream 文件流
 * 后台服务器没有可供下载的静态资源，返回的是一个文件流，则使用下面的方式
 * 通过URL.createObjectUrl生成url，创建a标签，href指向这个url，
 * download指向文件名，触发点击事件，进行下载
 *
 */

// 通过文件流方式下载
/**
 *
 * 若后端接口返回下载的文件链接 则可通过下面的方式下载
 */
const downloadFileStream = (FileStream, FileName) => {
  let downType = "";
  const typeAry = [".xls", ".xlsx", ".doc", ".docx", ".zip"];
  const index = typeAry.findIndex((item) => FileName.includes(item));
  if (index === -1) {
    // 默认下载Excel
    downType = `${FileName}.xls`;
  } else {
    downType = FileName;
  }
  const url = window.URL.createObjectURL(new Blob([FileStream]));
  let link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", FileName || "file");
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

//  通过直接的后端返回的链接下载文件非图片
const downloadFileName = (FileName) => {
  window.location.href = FileName;
};

// 下载图片
/**
 * 把图片转化为base64格式
 * 把base64转化为blob格式
 * 插入a标签进行下载
 *
 */

const downloadImage = async (img, fileName = "imageFile", width = "", height = "") => {
  console.log(img);
  const bs64 = await base64(img, 0, 0);
  let link = document.createElement("a");
  let blob = base64ToBlob(bs64);
  link.href = window.URL.createObjectURL(blob);
  link.setAttribute("download", fileName);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

// img => base64
function base64(imgSrc, width = "", height = "") {
  return new Promise((resolve, reject) => {
    let img = new Image();
    img.crossOrigin = "";
    img.src = imgSrc;
    img.onload = () => {
      const canvas = document.createElement("canvas");
      canvas.width = width || img.width;
      canvas.height = height || img.height;
      let ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
      let url = canvas.toDataURL();
      resolve(url);
    };
  });
}

// base64 => blob
function base64ToBlob(code) {
  let parts = code.split(";base64,");
  let contentType = parts[0].split(":")[1];
  let raw = window.atob(parts[1]);
  let rawLength = raw.length;
  let uInt8Array = new Uint8Array(rawLength);
  for (let i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }
  return new Blob([uInt8Array], { type: contentType });
}

export { downloadFileStream, downloadFileName, downloadImage };
